<template>
  <div id="content">
    <globle-linear-border>
      <el-card class="searchBox">
        <el-form :inline="true">
          <el-form-item label="姓名">
            <el-input v-model="pageQuery.otherParams.stuName" placeholder="输入学生姓名搜索" clearable @blur="getPageInfo" @clear="getPageInfo" />
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="pageQuery.otherParams.stuSex" placeholder="选择学生性别搜索" clearable @change="getPageInfo">
              <el-option label="男" value="1" />
              <el-option label="女" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否被删除">
            <el-select v-model="pageQuery.otherParams.isDelete" placeholder="选择是否被删除搜索" clearable @change="getPageInfo">
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </el-form-item>
        </el-form>
        <section>
          <el-button type="success" icon="Plus" @click="onAdd">添加学生</el-button>
          <el-button type="danger" icon="Minus" @click="onBatchDelete">批量删除</el-button>
          <el-upload :action="uploadUrl" :show-file-list="false" :on-progress="onProgress" :on-success="onSuccess" accept=".xlsx" :limit="1">
            <el-button type="warning" icon="Download">导入数据</el-button>
          </el-upload>
          <el-button type="warning" icon="Upload" @click="onExpose">导出数据</el-button>
        </section>
      </el-card>
    </globle-linear-border>

    <globle-linear-border style="margin-top: 20px">
      <el-card class="mainBox">
        <span v-if="tableData.rows">
          <el-table
            :border="true"
            stripe
            ref="tableRef"
            :data="tableData.rows"
            @selection-change="onSeleceChange"
            cell-class-name="table-cell"
            header-cell-class-name="table-header-cell"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column property="studentId" label="学号" width="140" show-overflow-tooltip />
            <el-table-column property="name" label="姓名" width="100" />
            <el-table-column label="性别">
              <template #default="scope">{{ scope.row.sex === 1 ? '男' : '女' }}</template>
            </el-table-column>
            <el-table-column property="major" label="专业" width="100" />
            <el-table-column property="college" label="学院" width="156" />
            <el-table-column property="qq" label="QQ号" width="120" />
            <el-table-column property="phone" label="手机号" width="120" />
            <el-table-column property="identityId" label="身份证号" width="180" />
            <el-table-column label="双体期数">
              <template #default="scope">{{ scope.row.stage + ' 期' }}</template>
            </el-table-column>
            <el-table-column label="部门">
              <template #default="scope">{{ scope.row.department + ' 部' }}</template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="180">
              <template #default="scope">
                <el-button type="primary" size="small" icon="Edit" @click="onEdit(scope.row)">修改</el-button>
                <el-button v-if="scope.row.isDelete === 0" type="danger" size="small" icon="Delete" @click="onDelete(scope.row)">删除</el-button>
                <el-button v-else type="warning" size="small" icon="RefreshRight" @click="onDelete(scope.row)">恢复</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            v-model:currentPage="pageQuery.pageParams.pageNum"
            v-model:page-size="pageQuery.pageParams.pageSize"
            :page-sizes="pageSizeOption"
            :background="true"
            :small="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="tableData.totalSize"
            @size-change="onSizeChange"
            @current-change="onCurrentChange"
          />
        </span>
      </el-card>
    </globle-linear-border>
    <!-- 弹窗 -->
    <suspense>
      <dialog-vue ref="dialogRef" @onReGetData="getPageInfo"></dialog-vue>
    </suspense>
  </div>
</template>

<script lang="ts" setup>
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, ElTable, UploadFile } from 'element-plus';
import { IPageParams, IPageRes, IStu, IFalseDelete, APIData } from '../../../type';
import { useUserStore } from '../../../store/user';
import { useAPI } from '../../../request/api';
import { useUtils } from '../../../utils';
//注意!!定义动态引入组件时需要使用defineAsyncComponent，并且在template中需要搭配suspense组件使用,它是一个异步组件解决方案。
const DialogVue = defineAsyncComponent(() => import('./Dialog.vue'));
const store = useUserStore();

onMounted(() => {
  // pageQuery.otherParams.stage = store.currentStage;
  getPageInfo();
});

store.$subscribe((args: any, states) => {
  if (pageQuery.otherParams.stage != states.currentStage) {
    pageQuery.otherParams.stage = states.currentStage;
    getPageInfo();
  }
});

const api = useAPI();
const utils = useUtils();
const dialogRef = ref();
const tableRef = ref<InstanceType<typeof ElTable>>();
const uploadUrl = `${api.baseUrl}/teacher/fileImport/stuInfo`;

let falseDeleteStuList = [] as Array<string>;
const pageSizeOption = [5, 10, 15, 20];
const pageQuery = reactive<IPageParams>({
  otherParams: {
    stuName: '',
    stuSex: '',
    stage: store.currentStage,
    isDelete: '',
    workId: store.userInfo.workId,
  },
  pageParams: {
    pageNum: 1,
    pageSize: pageSizeOption[1],
    sortField: '',
    sortType: '',
  },
});
const tableData = ref({} as IPageRes);

const onEdit = (row: IStu) => {
  dialogRef.value.openDialogByEdit(row);
};
// const onDelete = (deleteId: string) => {
//   utils.openDeleteMsgBox(() => {
//     falseDeleteStuList.push(deleteId);
//     falseDeleteStu();
//   });
// };

const onDelete = (row: IStu) => {
  if (row.isDelete === 0) {
    utils.openDeleteMsgBox(() => {
      falseDeleteStuList.push(row.id);
      falseDeleteStu();
    });
  } else if (row.isDelete === 1) {
    row.isDelete = 0;
    postModify(row, '恢复成功');
  }
};
const onAdd = () => {
  dialogRef.value.openDialogByAdd();
};

const postModify = async (row: IStu, message: string) => {
  const res: APIData = await api.save(row, store.role, 'stuInfo');
  if (res.code === 200) ElMessage.success(message);
  else ElMessage.error(res.message);
};

//上传进行
const onProgress = (evt: any, uploadFile: UploadFile) => {
  ElMessage.warning(`${uploadFile.name}正在上传中`);
};
//上传成功
const onSuccess = (response: APIData, uploadFile: UploadFile) => {
  if (response.code === 200) {
    getPageInfo();
    ElMessage.success(`${uploadFile.name}上传成功`);
  } else ElMessage.error(`${uploadFile.name}上传失败,请重试`);
};

//导出
const onExpose = () => {
  window.open(`${api.baseUrl}/teacher/fileExport/stuInfo?stage=${pageQuery.otherParams.stage}&workId=${store.userInfo.workId}`, '_self');
};

//分页大小
const onSizeChange = (val: number) => {
  pageQuery.pageParams.pageSize = val;
  getPageInfo();
};
//分页页码
const onCurrentChange = (val: number) => {
  pageQuery.pageParams.pageNum = val;
  getPageInfo();
};

//勾选(仅收集删除数据)
const onSeleceChange = (rowList: IStu[]) => {
  falseDeleteStuList = [] as Array<string>;
  rowList.forEach(item => {
    falseDeleteStuList.push(item.id);
  });
};
//勾选删除
const onBatchDelete = () => {
  if (falseDeleteStuList.length !== 0)
    utils.openDeleteMsgBox(() => {
      falseDeleteStu();
    });
  else ElMessage.error('未勾选任何数据');
};

const getPageInfo = async () => {
  const res = await api.findPage(pageQuery, store.role, 'stuInfo');
  tableData.value = res.data;
};
const falseDeleteStu = async () => {
  const res = await api.falseDelete(falseDeleteStuList, store.role, 'stuInfo');
  if (res.data) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    });
    getPageInfo();
  }
};
</script>

<style lang="scss" scoped>
#content {
  height: 100%;
  .searchBox {
    &-item {
      margin-right: 10px;
    }
    :deep(.el-form-item) {
      margin-bottom: 0;
    }
    :deep(.el-card__body) {
      display: flex;
      justify-content: space-between;
    }
    section {
      display: flex;
    }
    :deep(.el-input__wrapper) {
      width: 200px;
    }
  }
  .mainBox {
    :deep(.el-checkbox__inner) {
      background-color: var(--main-color);
      transition: background 0.3s ease;
    }
    :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
      background-color: var(--active-color);
      transition: background 0.3s ease;
    }
  }
}
</style>
